var rm = new Vue({
    el:'#main',
    data:{
        requirement:{
            name:null,
            num:1,
            price:null,
            bail:0,
            brokerage:null,
            categoryId:null,
            description:null,
            mode:'',
            platformId:'',
            type:null,
            goodsPath:null,
            rewardPath:null,
            type:1,
            daysNum:20,
            GoodsKeySearchList:[]
        },
        showGoodsPathImg:false,
        modeList:[],
        ptList:[],
        queryFirmInfo:{
            key:'',
            idPicUrl:''
        },
        info:{
            price:'10'
        }
    },
    created:function(){
        //获取平台类型
        plAjax = $.ajax({
            type: "GET",
            url: baseURL + "/coustomer/getPlatform",
            dataType: "json",
            async: true,
            contentType:"application/json",
            data:null,
            success: function(r){
                if (r.code===0) {
                    rm.ptList = r.data;
                }else{
                    alert(r.info);
                }
            }
        });
        //获取收费类型
        var feeParam = {"code":"001"};
        modeAjax =  $.ajax({
            type: "POST",
            url: baseURL + "/programa/getByPCode",
            dataType: "json",
            async: true,
            contentType:"application/json",
            data:JSON.stringify(feeParam),
            success: function(r){
                if (r.code===0) {
                    rm.modeList = r.data;
                }else{
                    alert(r.info);
                }
            }
        });
        //复制任务相关
        if(null != getParam("id") && ''!= getParam("id")){
            var param ={
                'id':getParam("id")
            }
            $.ajax({
                type: "GET",
                url: baseURL + "/merchant/getRequirementById",
                dataType: "json",
                async: true,
                contentType:"application/json",
                data:param,
                success: function(r){
                    if (r.code===0) {
                        rm.requirement = r.data;
                        $("#goodsPathImg").attr("src", rm.requirement.goodsPath);
                        $("#goodsPathImg").show();
                        $("#rewardPathImg").attr("src", rm.requirement.rewardPath);
                        $("#rewardPathImg").show();
                        var num =0;
                        if(rm.requirement.GoodsKeySearchList && rm.requirement.GoodsKeySearchList.length){
                            num=rm.requirement.GoodsKeySearchList.length;
                        }
                        debugger;
                        for(var i=0;i<5-num;i++){
                            if(rm.requirement.GoodsKeySearchList ==null){
                                rm.requirement.GoodsKeySearchList = new Array();
                            }
                            rm.requirement.GoodsKeySearchList.push({
                                'GoodsKeySearch':{
                                    'goodsRange':1,
                                    'goodsRank':1,
                                    'keyWord':'',
                                    'pageInfo':'',
                                    'priceStart':'',
                                    'priceEnd':'',
                                    'sendAddress':''
                                }
                            })
                        }
                        setTimeout(function () {
                            document.getElementById('description').contentWindow.editor.html(r.data.description);
                        },2000);
                    }else{
                        alert(r.info);
                    }
                }
            });
        }else{
            setTimeout(function () {
                document.getElementById('description').contentWindow.editor.html(requirement_html)
            },2000)
            //默认5个关键字
            for(var i=0;i<5;i++){
                if(this.requirement.GoodsKeySearchList ==null){
                    this.requirement.GoodsKeySearchList = new Array();
                }
                this.requirement.GoodsKeySearchList.push({
                    'GoodsKeySearch':{
                        'goodsRange':1,
                        'goodsRank':1,
                        'keyWord':'',
                        'pageInfo':'',
                        'priceStart':'',
                        'priceEnd':'',
                        'sendAddress':''
                    }
                })
            }
            $.when(plAjax , modeAjax).done(function () {
                rm.requirement.mode = rm.modeList[0].code;
                rm.requirement.platformId = rm.ptList[0].id;
            })
        }
    },
    methods: {
        countMoney:function () {
            if(this.requirement.num != '' && this.requirement.brokerage!='' && this.requirement.price!=''){
                this.requirement.bail=(parseFloat(this.requirement.brokerage)+parseFloat(this.requirement.price))*this.requirement.num;
            }else{
                this.requirement.bail=0;
            }
        },
        baseFileAjax:function (data,method){
            $.ajax({
                url: '' ,
                type: 'POST',
                data: data,
                dataType: 'JSON',
                cache: false,
                processData: false,
                contentType: false,
                success: method,
                error: function (returndata) {
                    alert("Connection error");
                }
            });
        },
        getObjectURL:function(file) {
            var url = null;
            if (window.createObjectURL!=undefined) {
                url = window.createObjectURL(file) ;
            } else if (window.URL!=undefined) { // mozilla(firefox)
                url = window.URL.createObjectURL(file) ;
            } else if (window.webkitURL!=undefined) { // webkit or chrome
                url = window.webkitURL.createObjectURL(file) ;
            }
            return url ;
        },
        handleFileChange:function(e){

            // var rm=this;
            // var file = e.target.files[0];
            // var supportedTypes = ['image/jpg', 'image/jpeg', 'image/png'];
            // if (file && supportedTypes.indexOf(file.type) >= 0) {
            //     debugger;
            //     this.baseFileAjax(new FormData($( "#reqForm" )[0]),function(result){
            //         if(result.ret==0){
            //             //提交成功后
            //             //将图片上传到后台，得到后台图片的路径。
            //             rm.queryFirmInfo["idPicUrl"]=result.url;
            //             // $("#reqForm").formValidation('revalidateField', "idPicUrl");
            //         }else{
            //             layer.msg("修改图片失败！")
            //         }
            //
            //     })
            // } else {
            //     this.requirement.goodsPath=null;
            //     layer.alert('文件格式只支持：jpg、jpeg 和 png');
            // }
        },
        goodsPathChange:function (e) {
            $("#goodsPathOriganl").val(e.currentTarget.files[0].name);
        },
        rewardPathChange:function (e) {
            $("#rewardPathOriganl").val(e.currentTarget.files[0].name);
        },
        subRequirement:function(){
            var formData = new FormData($("#reqForm")[0]);
            var goodsKeyWordSerch = [];
            $($(".goods_key_search").find("tr")[0]).find(".goodsRange").val();
            $(".goods_key_search").find("tr").each(function(){
            	var data={
            			goodsRange:$(this).find(".goodsRange").val()?$(this).find(".goodsRange").val():0,
            			goodsRank:$(this).find(".goodsRank").val()?$(this).find(".goodsRank").val():0,
            			keyWord:$(this).find("input[name='keyWord']").val()?$(this).find("input[name='keyWord']").val():"",
            			pageInfo:$(this).find("input[name='pageInfo']").val()?$(this).find("input[name='pageInfo']").val():"",
            			sendAddress:$(this).find("input[name='sendAddress']").val()?$(this).find("input[name='sendAddress']").val():"",
            	}
            	goodsKeyWordSerch.push(data);
            });
            $("#goodsKeySearchLists").val(JSON.stringify(goodsKeyWordSerch));
            $.ajax({
                url : baseURL+ "/merchant/publish",
                type : 'POST',
                data : formData,
                cache: false,
                async: false,
                processData : false,  //必须false才会避开jQuery对 formdata 的默认处理
                contentType : false,  //必须false才会自动加上正确的Content-Type
                success: function (res) {
                    alert("发布成功，请联系管理员审核！",function () {
                        top.location.href ="/index.html#merchant/merchantmain.html";
                    });
                },
                error: function (res) {
                    alert(res.info,function () {
                      // location.reload()
                    });
                }
            });
        }
    },
    mounted:function () {


        $("#endTime").datetimepicker();
        var cusparam ={
            "name":"requirement_html"
        }
        //获取商家输入的时候的模板内容
        //图片上传
        function getObjectURL(file) {
            var url = null;
            if (window.createObjectURL!=undefined) {
                url = window.createObjectURL(file) ;
            } else if (window.URL!=undefined) { // mozilla(firefox)
                url = window.URL.createObjectURL(file) ;
            } else if (window.webkitURL!=undefined) { // webkit or chrome
                url = window.webkitURL.createObjectURL(file) ;
            }
            return url ;
        }
        $("#goodsPath1").change(function(e){
            var file = e.target.files[0];
            var supportedTypes = ['image/jpg', 'image/jpeg', 'image/png'];
            if (file && supportedTypes.indexOf(file.type) >= 0) {
            var objUrl = getObjectURL(this.files[0]) ;//获取文件信息
            console.log("objUrl = "+objUrl);
            if (objUrl) {
                $("#goodsPathImg").attr("src", objUrl);
            }
            } else {
                rm.requirement.goodsPath=null;
                $("#goodsPathImg").attr("src", "");
                layer.alert('文件格式只支持：jpg、jpeg 和 png');
            }
        })
        $("#rewardPath1").change(function(e){
            var file = e.target.files[0];
            var supportedTypes = ['image/jpg', 'image/jpeg', 'image/png'];
            if (file && supportedTypes.indexOf(file.type) >= 0) {
                var objUrl = getObjectURL(this.files[0]) ;//获取文件信息
                console.log("objUrl = "+objUrl);
                if (objUrl) {
                    $("#rewardPathImg").attr("src", objUrl);
                }
            } else {
                rm.requirement.rewardPath=null;
                $("#rewardPathImg").attr("src", "");
                layer.alert('文件格式只支持：jpg、jpeg 和 png');
            }
        })






        //表单验证
        $("#reqForm").bootstrapValidator({
            live: 'enabled',//验证时机，enabled是内容有变化就验证（默认），disabled和submitted是提交再验证
            excluded: [':disabled', ':hidden', ':not(:visible)'],//排除无需验证的控件，比如被禁用的或者被隐藏的
            submitButtons: '#subReq',//指定提交按钮，如果验证失败则变成disabled，但我没试成功，反而加了这句话非submit按钮也会提交到action指定页面
            message: '通用的验证失败消息',//好像从来没出现过
            feedbackIcons: {//根据验证结果显示的各种图标
                valid: 'glyphicon glyphicon-ok',
                invalid: 'glyphicon glyphicon-remove',
                validating: 'glyphicon glyphicon-refresh'
            }
            ,
            fields: {
                name: {
                    enabled: true,
                    validators: {
                        notEmpty: {//检测非空,radio也可用
                            message: '名字必须输入'
                        },
                        stringLength: {//检测长度
                            min: 2,
                            max: 15,
                            message: '长度必须在2-15之间'
                        }
                    }
                },
                price:{
                    enbled:true,
                    validators: {
                        notEmpty: {//检测非空,radio也可用
                            message: '单价必须输入'
                        },
                        regexp: {//正则验证
                            regexp: /^[0-9_\.]+$/,
                            message: '单价必须为数字'
                        },
                    }
                },
                brokerage:{
                    enbled:true,
                    validators:{
                        notEmpty: {//检测非空,radio也可用
                            message: '奖励金必须输入'
                        },
                        regexp: {//正则验证
                            regexp: /^[0-9_\.]+$/,
                            message: '奖励金必须为数字'
                        }
                    }
                },
                goodsPath1:{
                    enbled:true,
                    validators:{
                        notEmpty: {//检测非空,radio也可用
                            message: '请上传商品图片'
                        }
                    }
                },
                rewardPath1:{
                    enbled:true,
                    validators:{
                        notEmpty: {//检测非空,radio也可用
                            message: '请上传奖励图片'
                        }
                    }
                },
                mode:{
                    enbled:true,
                    validators:{
                        notEmpty: {//检测非空,radio也可用
                            message: '请选择收费模式'
                        }
                    }
                },
                platformId:{
                    enbled:true,
                    validators:{
                        notEmpty: {//检测非空,radio也可用
                            message: '请选择平台'
                        }
                    }
                }
            }
        });
        //数据提交
        $("#subReq").click(function(){
            $("#descriptionValue").val(document.getElementById('description').contentWindow.editor.html());
            $("#reqForm").bootstrapValidator('validate');//提交验证
            if ($("#reqForm").data('bootstrapValidator').isValid()) {//获取验证结果，如果成功，执行下面代码
                //增加一个发布预审核
                var preParam ={
                    "price":rm.requirement.price,
                    "brokerage":rm.requirement.brokerage,
                    "mode":rm.requirement.mode,
                    "num":rm.requirement.num
                }
                $.ajax({
                    type: "POST",
                    url: baseURL + "/merchant/preAduit",
                    dataType: "json",
                    async: true,
                    contentType:"application/json",
                    data:JSON.stringify(preParam),
                    success: function(r){
                        //试用详情
                        console.log(r);
                        rm.info=r.data;
                        console.log(r.data);
                        if (r.code!=0) {
                            $("#subRequirement").attr("disable",true);
                            var msg = "您的当前可用余额为："+r.data.balance+"元,本次发布保证金为："+r.data.total+"元，您的余额不足，请充值后再操作！";
                            rm.info['msg']=msg;
                        }
                        layer.open({
                            type: 1,
                            skin: 'layui-layer-rim', //加上边框
                            area: ['540px', '540px'], //宽高
                            content: $("#infoConfirm")
                        });
                    }
                });
                
            }

        })

    }
});